package com.bz.controller;

import com.bz.entity.UserBuyer;
import com.bz.service.UserBuyerService;
import com.bz.util.VerifyCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/user")
@Slf4j//导入日志包
public class UserBuyerController {


    @Autowired
    private UserBuyerService userBuyerService;


    /**
     * 生成验证码
     *
     * @return
     */

    @GetMapping("/getImage")
    public String getImage(HttpServletRequest request) throws IOException {
        //使用工具类生成验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);

        //前后端分离的项目没有session的说法，放在最大的作用域中 servletContext,全局唯一
        request.getServletContext().setAttribute("code", code);
        System.out.println("验证码:" + code);

        // 内存中的输出流
        ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();


        VerifyCodeUtils.outputImage(120, 30, byteOutputStream, code);

        String s = "data:image/png;base64," + Base64Utils.encodeToString(byteOutputStream.toByteArray());
        return s;

    }

    //TODO
    //@RequestBody 将传入的参数封装成对象
    @PostMapping("/register")
    public Map<String, Object> save(@RequestBody UserBuyer user, String code, HttpServletRequest request) {
        String key = (String) request.getServletContext().getAttribute("code");
        log.info("用户信息：[{}]", user.toString());
        log.info("用户输入的验证码信息：[{}]", code);
        log.info("生成的的验证码信息：[{}]", key);
        Map<String, Object> map = new HashMap<>();
        try {


            if (key.equalsIgnoreCase(code)) {
                userBuyerService.register(user);
                map.put("status", true);
                map.put("msg", "提示：注册成功");

            } else {
                throw new RuntimeException("验证吗错误");
            }


        } catch (Exception e) {
            map.put("status", false);
            map.put("msg", "提示:" + e.getMessage());

        }
        return map;
    }

    //ToDO    RequestBody

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody UserBuyer user) {
        System.out.println("user=login" + user);
        Map<String, Object> map = new HashMap<>();

        try {
            UserBuyer uDB = userBuyerService.login(user);
            map.put("msg", "登录成功");
            map.put("state", true);
            map.put("user", uDB);
        } catch (Exception e) {
            map.put("state", false);
            map.put("msg", e.getMessage());
        }
        return map;

    }



}
